package com.itheima.aop;

import cn.hutool.json.JSONUtil;
import com.aliyun.properties.JwtProperties;
import com.itheima.common.R;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;

import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
@Aspect
public class OperateLogAspect {


    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JwtProperties jwtProperties;

    // @Around("execution(public * com.itheima.controller.*.*(..))")
    @Around("@annotation(com.itheima.annotion.Log)")
    public Object log(ProceedingJoinPoint point) throws Throwable {
        Long begin = System.currentTimeMillis();
        Object proceed = point.proceed();
        R r = (R) proceed;
        if (r.getData() != null) {
            return proceed;
        }
        Long costTime = System.currentTimeMillis() - begin;
        log.info("切面" + r);
        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String jwt = servletRequest.getHeader("Token");
        Map<String, Object> map = Jwts.parser()
                .setSigningKey(jwtProperties.getSecretKey())
                .parseClaimsJws(jwt).getBody();
        String userId = map.get("id").toString();


        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUser(Integer.valueOf(userId));
        operateLog.setCostTime(costTime);
        operateLog.setReturnValue(r.toString());
        operateLog.setClassName(point.getTarget().getClass().getName());
        operateLog.setMethodName(point.getSignature().getName());
        operateLog.setMethodParams(JSONUtil.toJsonStr(point.getArgs()));
        operateLog.setOperateTime(LocalDateTime.now());

        operateLogMapper.insert(operateLog);
        return proceed;

    }
}
